from flask import Blueprint, request, jsonify
from flaskapp.entity.Consultation import Consultation
from flaskapp.entity.User import User
from flaskapp.util.Result import Result
from flaskapp.util.Sqlalchemy import db
from datetime import datetime
from flaskapp.util.Redprint import Redprint
from flaskapp.entity.Consultation import Consultation

api = Redprint('consultation')

# 创建新的意见反馈（给管理员发意见）
@api.route('/create', methods=['POST'])
def create_consultation():
    """用户提交新的意见反馈"""
    data = request.get_json()
    user_id = data.get('user_id')
    content = data.get('content')

    if not user_id or not content:
        return Result.error(400, '缺少必要参数')

    # 创建咨询记录
    consultation = Consultation(
        user_id=user_id,
        content=content,
        submitted_at=datetime.now(),
        status='未处理'  # 默认状态为未处理
    )
    
    try:
        db.session.add(consultation)
        db.session.commit()
        return Result.success({
            'message': '意见提交成功',
            'consultation_id': consultation.consultation_id
        })
    except Exception as e:
        db.session.rollback()
        return Result.error(500, f"提交失败: {str(e)}")

# 获取用户的所有意见咨询
@api.route('/user/<int:user_id>', methods=['GET'])
def get_user_consultations(user_id):
    """获取用户所有提交的意见咨询"""
    consultations = Consultation.query.filter_by(user_id=user_id).all()
    print(consultations)
    if not consultations:
        return Result.error(404, '没有找到任何意见咨询')

    return Result.success([consultation.to_dict() for consultation in consultations], '获取用户的意见反馈成功')

@api.route('/consultationsList', methods=['GET'])
def get_consultations():
    content = request.args.get('content', '').strip()
    status = request.args.get('status', '').strip()

    # 构建查询
    query = db.session.query(
        Consultation.consultation_id,
        User.account_name.label('user_name'),
        Consultation.content,
        Consultation.submitted_at,
        Consultation.status,
        Consultation.reply
    ).join(User, Consultation.user_id == User.user_id)

    # 添加 content 模糊查询
    if content:
        query = query.filter(Consultation.content.ilike(f'%{content}%'))

    # 添加 status 精准筛选
    if status:
        query = query.filter(Consultation.status == status)

    results = query.all()

    return jsonify([
        {
            'consultation_id': r.consultation_id,
            'user_name': r.user_name,
            'content': r.content,
            'submitted_at': r.submitted_at.strftime('%Y-%m-%d %H:%M:%S') if r.submitted_at else None,
            'status': r.status,
            'reply': r.reply
        } for r in results
    ])

@api.route('/updateStatus/<int:consultation_id>', methods=['POST'])
def update_status(consultation_id):
    data = request.get_json()
    new_status = data.get('status')
    if new_status not in ['未处理', '处理中', '已完成']:
        return jsonify({'message': '无效状态'}), 400

    consultation = Consultation.query.get(consultation_id)
    if not consultation:
        return jsonify({'message': '未找到反馈'}), 404

    consultation.status = new_status
    if new_status == '已完成':
        consultation.processed_at = datetime.now()  #  记录完成时间

    db.session.commit()
    return jsonify({'message': '状态更新成功'})


@api.route('/reply/<int:consultation_id>', methods=['POST'])
def submit_reply(consultation_id):
    data = request.get_json()
    reply = data.get('reply')

    consultation = Consultation.query.get(consultation_id)
    if not consultation:
        return jsonify({'message': '未找到该反馈'}), 404

    consultation.reply = reply
    db.session.commit()

    return jsonify({'message': '回复成功'})

